<template>
  <div class="search-suggestion">
    <div v-if="suggestionList[0]">
      <van-cell
        v-for="(item, index) in suggestionList"
        :key="index"
        @click="$emit('search', item)"
        icon="search">
        <template v-slot:title>
          <span v-html="resultItem(item)"></span>
        </template>
      </van-cell>
    </div>

    <van-cell
      class="no-list"
      v-else
      title="暂无数据"
    >
    </van-cell>
  </div>
</template>

<script>
// 2. 导入方法
import {getSuggestion} from '@/api/search'

// 1. 导入 lodash
import { debounce } from 'lodash'

export default {
  props: ['searchText'], // 1
  data() {
    return {
      suggestionList: []
    }
  },
  watch: {
    searchText: {
      deep: true,
      immediate: true,
      // 2. 使用
      handler: debounce(function(newValue) {
        this.getSuggestionFn(newValue)
      }, 150)
    }
  },
  methods: {
    async getSuggestionFn(newValue) {
      // 4. 发请求 传递参数 q query 后台要求字段 查询
      const {data: {data: {options}}} = await getSuggestion({q: newValue})

      this.suggestionList = options
    },
    resultItem(item) {
      // 1. 查找所有符合的元素 g global 全部查找
      let reg = new RegExp(this.searchText, 'ig')
      // 2. 把符合的字符 替换成 span标签包裹的
      let str = item.replace(reg, `<span class="active">${this.searchText}</span>`)

      // 3. 将操作完的 字符串 返回
      return str
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  .no-list {
    text-align: center;
    color: #333;
  }

  /deep/.active {
    color: red;
  }
}
</style>
